package com.air.aspect;


import com.air.annotation.AutoFill;
import com.air.constant.AutoFillConstant;
import com.air.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自定义切面类，用于实现公共字段自动填充
 */
@Aspect
@Component
@Slf4j
public class AutoFillAspect {


    /**
     * 定义切入点
     */
    @Pointcut("execution(* com.air.mapper.*.*(..)) && @annotation(com.air.annotation.AutoFill)")
    public void autoFillPointCut() {}

    /**
     * 定义前置通知,在通知中进行公共字段的赋值
     */
    @Before("autoFillPointCut()")
    public void autoFill(JoinPoint joinPoint) {

        //获取操作类型
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        OperationType value = signature.getMethod().getAnnotation(AutoFill.class).value();

        //获取当前被拦截的方法的参数-实体对象
        Object[] args = joinPoint.getArgs();
        if (args.length == 0 || args.length==0){
            return;
        }
        Object entity = args[0];
        //准备赋值的数据
        LocalDateTime now = LocalDateTime.now();

        //根据操作类型来决定用哪个字段进行反射赋值
        if (value == OperationType.INSERT) {
            try {
                //通过反射获取到set方法，并调用set方法进行赋值
                entity.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class).invoke(entity, now);
                entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class).invoke(entity, now);

            } catch (Exception e) {
                e.printStackTrace();
            }
        } else if (value == OperationType.UPDATE) {
            try{
                //通过反射获取到set方法，并调用set方法进行赋值
                entity.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class).invoke(entity, now);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
